package org.fight.logic.fightbo;

import java.util.List;

import org.fight.bean.AbstractFight;
import org.fight.bean.FightStatusEnum;
import org.fight.bean.AbstractFight.NetFrame;
import org.fight.cache.FightCache;
import org.fight.cache.FightPlayerCache;
import org.fight.manager.FightManager;
import org.fight.net.KcpConstant;
import org.fight.protobuf.C2SFightMsg.ReqEndFight;
import org.fight.protobuf.C2SFightMsg.ReqEnterFight;
import org.fight.protobuf.C2SFightMsg.ReqOperateFight;
import org.fight.protobuf.C2SFightMsg.ReqPullNetFrame;
import org.fight.protobuf.S2CFightMsg;
import org.fight.protobuf.S2CFightMsg.RespPullNetFrame;

import com.sojoys.artifact.exception.AbstractLogicModelException;
import com.sojoys.artifact.factory.session.ISession;

/**
 * @author : DengYing
 * @CreateDate : 2018年3月1日 下午12:07:58
 * @Description ：Please describe this document
 */
public class FightBOImpl implements FightBO {
	public static final byte[] RESULT = new byte[0];
	@Override
	public byte[] enterFight(ISession session, ReqEnterFight param) throws AbstractLogicModelException {
		
		// 创建战斗玩家
		FightPlayer fightPlayer = new FightPlayer();
		fightPlayer.setPid(param.getPid());
		fightPlayer.setSession(session);
		FightPlayerCache.put(fightPlayer);
		
		
		session.setAttr(KcpConstant.PLAYER, fightPlayer);
		
		// 取得战斗
		AbstractFight fight = FightCache.get(param.getFightId());
		if (fight != null && fight.getStatus() == FightStatusEnum.RUNING) {
			FightManager.me().destroyFight(fight);
			fight = FightManager.me().createFight(param.getFightId());
		}
		if (fight==null) {
			fight = FightManager.me().createFight(param.getFightId());
		}
		// 设置战斗
		session.setAttr(KcpConstant.FIGHT, FightCache.get(param.getFightId()));
		
		FightManager.me().enterFight(fight, fightPlayer);
		
		return null;
	}

	@Override
	public byte[] operateFight(ISession session, ReqOperateFight param) throws AbstractLogicModelException {
		FightPlayer fightPlayer = session.getAttr(KcpConstant.PLAYER);
		AbstractFight fight = session.getAttr(KcpConstant.FIGHT);
		FightManager.me().operate(fightPlayer, fight, param);
		return null;
	}

	@Override
	public byte[] pullNetFrame(ISession session, ReqPullNetFrame param) throws AbstractLogicModelException {
		AbstractFight fight = session.getAttr(KcpConstant.FIGHT);
		List<NetFrame> netFrames = FightManager.me().pullNetFrame(fight, param.getFromIndex());
		List<S2CFightMsg.NetFrame> framesMsgs = FightManager.me().buildNetFramesMsg(netFrames);
		return RespPullNetFrame.newBuilder().addAllNetFrames(framesMsgs).build().toByteArray();
	}

	@Override
	public byte[] endFight(ISession session, ReqEndFight param) throws AbstractLogicModelException {
		AbstractFight fight = session.getAttr(KcpConstant.FIGHT);
		FightManager.me().destroyFight(fight);
		return null;
	}

}
